package com.microwintech.boardingtreasure.db.dao;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.microwintech.boardingtreasure.tool.CommonTool;

/**
 * Created by Administrator on 2014/11/27.
 */
public class CityOpenHelper extends SQLiteOpenHelper {
    private static CityOpenHelper dbInstance = null;

    private static SQLiteDatabase sqliteDb = null;
    private static String DATA_FILE = CommonTool.DATA_SAFETY_FILE + "/city.db";
    private Context mContext;
    private static int VERSION = 1000;

    /**
     * 显示调用父类的方法
     *
     * @param context
     */
    public CityOpenHelper(Context context) {
        //context上下文       name数据库名称      factory游标工厂   version数据库文件的版本号
        super(context, DATA_FILE, null, VERSION);
        //如果数据库被创建 那么数据库文件会被保存在当前应用所在的<包>/databases
        this.mContext = context;
    }

    /**
     * 单例模式 返回实例
     *
     * @param context
     * @return
     */
    public synchronized static CityOpenHelper getInstance(Context context) {
        if (dbInstance == null) {
            dbInstance = new CityOpenHelper(context);
        }
        return dbInstance;
    }

    public CityOpenHelper(Context context, String name, int version) {
        this(context, name, null, version);
    }

    public CityOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
        this.mContext = context;
        this.VERSION = version;
    }

    public void close() {
        if (sqliteDb != null) {
            sqliteDb.close();
        }
    }


    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
    }

    //该函数是在第一次创建的时候执行，实际上是第一次得到SQLiteDatabase对象的时候才会调用这个方法
    @Override
    public void onCreate(SQLiteDatabase db) {
        // db.execSQL("");
    }

    /**
     * 查询*
     */
    public Cursor read(String sqlstr) {
        Cursor cur = sqliteDb.rawQuery(sqlstr, null);
        return cur;
    }

    /**
     * 当数据库文件的版本号发生改变时调用
     */
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    }

    public void closeAll(Cursor cursor, SQLiteDatabase sqliteDatabase, CityOpenHelper helper) {
        try {
            if (cursor != null) {
                cursor.close();
            }
            if (sqliteDatabase != null) {
                sqliteDatabase.close();
            }
            if (helper != null) {
                helper = null;
            }
        } catch (Exception e) {
        }
    }


}
